import { getRootDir, joinPath } from "./enhance/path.node";
import { nodeFileSystem } from "./enhance/fs.node";
import { writeVueTSFile } from "./enhance/vue-ts.file";
import { writeVueJSFile } from "./enhance/vue-js.file";
import * as process from "process";
import { toLineStyle } from "./enhance/string";
import { writeUniJSFile } from "./enhance/uni-js.file";

export interface Config {
    name: string;
    type: "vue-ts" | "vue-js" | "uni-js";
    root: string;
    codeRoot: string;
    styleType: "css" | "less" | "scss" | "sass";
    initStyles: string[];
    rootTag: string;
    rewrite: boolean;
    folderNameStyle: "" | "-";
}

const rootDir = getRootDir();
const configFile = joinPath(rootDir, "../cli-proj.config.json");
let config: Config;
const projectName = process.argv[2];
if (nodeFileSystem.existsSync(configFile)) {
    const configList: Config[] = JSON.parse(nodeFileSystem.readFileSync(configFile, "utf8")) as Config[];
    config = Object.assign({
        type: "vue-ts",
        codeRoot: "src",
        styleType: "scss",
        initStyles: [],
        rootTag: "div",
        rewrite: false,
        folderNameStyle: "",
    }, configList.find(item => {
        return item.name === projectName;
    }));
}

if (config) {
    const actionFolder = process.argv[3];
    const componentName = process.argv[4];
    if (actionFolder && componentName) {
        let folder;
        if (config.folderNameStyle) {
            folder = joinPath(config.root, config.codeRoot, actionFolder, toLineStyle(componentName, config.folderNameStyle))
        } else {
            folder = joinPath(config.root, config.codeRoot, actionFolder, componentName)
        }
        if (!nodeFileSystem.existsSync(folder)) {
            nodeFileSystem.mkdirSync(folder, {
                recursive: true,
            });
        }
        if (process.argv[5]) {
            config.rootTag = process.argv[5];
        }
        if (process.argv[6] && process.argv[6] !== "false" && process.argv[6] !== "0") {
            config.rewrite = true;
        }
        switch (config.type) {
            case "vue-ts":
                writeVueTSFile(folder, componentName, config);
                break;
            case "vue-js":
                writeVueJSFile(folder, componentName, config);
                break;
            case "uni-js":
                writeUniJSFile(folder, componentName, config);
                break;
        }
    }
}
